﻿using System;
using System.Data;
using sscore;

namespace DM4
{
    public partial class DM4
    {
        private bool ModuleExists(string moduleCode)
        {
            return (_modules.ContainsKey(moduleCode.ToUpper()));
        }

        public XMLInfo GetModulesList(int grpId = DM4Consts.DefaultNULLId)
        {
            BeginFunction("GetModulesList");
            WriteLog(String.Format("Get modules info list for group id [{0}]", grpId));

            XMLInfo xi = new XMLInfo();

            DataTable dt = new DataTable("modules");
            dt.Columns.Add("mod_code", typeof(string));
            dt.Columns.Add("mod_filename", typeof(string));
            dt.Columns.Add("mod_short_filename", typeof(string));
            dt.Columns.Add("mod_grp", typeof(int));
            dt.Columns.Add("mod_disabled", typeof(string));
            dt.Columns.Add("mod_help", typeof(string));
            dt.Columns.Add("mod_description", typeof(string));
            dt.Columns.Add("mod_version", typeof(string));

            try
            {
                foreach (ModuleEntry me in _modules.Values)
                {
                    if (grpId != DM4Consts.DefaultNULLId && me.GrpId != grpId) continue;

                    DataRow dr = dt.NewRow();
                    dr["mod_code"] = me.Code;
                    dr["mod_filename"] = me.FileName;
                    dr["mod_short_filename"] = me.ShortFileName;
                    dr["mod_grp"] = me.GrpId;
                    dr["mod_disabled"] = me.Disabled;
                    dr["mod_description"] = me.Description;
                    dr["mod_version"] = me.Version;
                    dr["mod_help"] = me.Help.XML; //only xml returned

                    dt.Rows.Add(dr);
                }

                xi.Load(dt);
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, MessageType.Error);
            }

            EndFunction("GetModulesList");
            return xi;
        }

        public XMLInfo GetModuleHelp(string moduleCode)
        {
            BeginFunction("GetModuleHelp");
            
            XMLInfo xi = new XMLInfo();
            try
            {
                WriteLog(String.Format("Get modulehelp for module [{0}]", moduleCode));

                if (ModuleExists(moduleCode))
                {
                    xi = _modules[moduleCode.ToUpper()].Help;
                }
                else
                    WriteLog(String.Format("Module with code [{0}] not found", moduleCode), MessageType.Error);
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, MessageType.Error);
            }

            EndFunction("GetModuleHelp");
            return xi;
        }
    }
}
